package seatiger.tomcat.catalina.connector;

import seatiger.tomcat.coyote.Request;
import seatiger.tomcat.util.buf.ByteChunk;

import java.io.IOException;

/**
 * 这是被tomcat中request对象中使用的buffer，用于从读取请求体的内容
 */
public class InputBuffer implements ByteChunk.ByteInputChannel {

    /**
     * 默认buffer大小读取请求体数据
     */
    public static final int DEFAULT_BUFFER_SIZE = 8*1024;

    /**
     * byte buffer
     */
    private ByteChunk bb;

    private int size;

    /**
     * 关联的coyote request
     */
    private Request coyoteRequest;

    public InputBuffer(int size) {
        bb = new ByteChunk(size);
        this.size = size;
        bb.setByteInputChannel(this);
        bb.setLimit(size);
    }

    public InputBuffer() {
        this(DEFAULT_BUFFER_SIZE);
    }

    public void setCoyoteRequest(Request coyoteRequest) {
        this.coyoteRequest = coyoteRequest;
    }

    public int read(byte[] b, int off, int len) throws IOException{
        return bb.substract(b, off, len);
    }

    @Override
    public int realReadBytes(byte[] cbuf, int off, int len) throws IOException {
        int result = coyoteRequest.doRead(bb);
        return result;
    }
}
